import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../event/auth_face_success_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/serial_port_helper.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import 'clipper.dart';


class AuthDialog{

  RxString authType = RxString('1');
  RxBool initialize = RxBool(false);

  late List<CameraDescription> _cameras;
  CameraController? controller;

  Timer? _timer;

  var countTime = 120;

  CameraImage? currentImage;

  _openCamera() async {
    _cameras = await availableCameras();
    controller = CameraController(_cameras[0], ResolutionPreset.max);
    controller!.initialize().then((_) {
      initialize.value = true;
      // _startImageStream();
      _start();
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            toastError('Camera CameraAccessDenied');
            break;
          default:
            toastError('camera error');
            _disposeCamera();
            break;
        }
      }
    });
  }

  _disposeCamera(){
    initialize.value = false;
    controller?.dispose();
    controller = null;
    _timer?.cancel();
    _timer = null;
  }

  _start(){
    countTime = settingEntity.fastCountdown??20;
    _timer = Timer.periodic(const Duration(seconds: 2), (timer) {
      if (countTime <= 0) {
        if(_timer!=null){
          _timer!.cancel();
          _timer = null;
          toastWarn('人脸认证超时');
        }
        return;
      }
      countTime = countTime-2;
      _computeTakePicture();
    });
  }

  _computeTakePicture() async {
    if (controller != null) {
      XFile file = await controller!.takePicture();
      // var data = await compute(_sendPicture, file);
      var bytes = await file.readAsBytes();
      String base64 = base64Encode(bytes);
      String base64Image = "data:image/png;base64,$base64";
      var data = await faceSearch(base64Image);
      File f = File.fromUri(Uri.file(file.path));
      f.delete();
      if(data.$1 != null){
        if(controller != null && currentTask.uid == null){
          currentTask.uid = data.$1.userId;
          eventFactory.fire(AuthFaceSuccessEvent());
          timer.cancel();
          _disposeCamera();
        }

      }else{
        toastWarn('${data.$2}');
      }
    }
  }


   static Future _sendPicture(XFile file)  async {
     var bytes = await file.readAsBytes();
     String base64 = base64Encode(bytes);
     String base64Image = "data:image/png;base64,$base64";
     var data = await faceSearch(base64Image);
     File f = File.fromUri(Uri.file(file.path));
     f.delete();
     return data;
    }


  authTypeDialog() async {
    timer.startCountDown(CountDownMode.fast,(){
      _disposeCamera();
      idSerialPortHelper?.close();
      idSerialPortHelper = null;
      Get.until((route) => route.isFirst);
    });
    if(settingEntity.auth != null){
      authType.value = settingEntity.auth!;
    }
    _onTap(authType.value);

    Get.defaultDialog(
      title: "",
      barrierDismissible: false,
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 320.w,
        height: 405.h,
        decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/dialog_bg.png",
              ),
            )
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Positioned(
                top: 5.h,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Text('身份认证',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 18.sp,)),
                )
            ),
            Positioned(
                top: 5.h,
                right: 28.w,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Obx(() => Text('${timer.fastTime.value}s',style: TextStyle(color: Colors.white,fontSize: 10.sp),textAlign: TextAlign.center,)),
                )
            ),

            Positioned(
                top: 5.h,
                right: 10.w,
                child: InkWell(
                  onTap: (){
                    _disposeCamera();
                    timer.cancel();
                    idSerialPortHelper?.close();
                    idSerialPortHelper = null;
                    Get.back();
                  },
                  child: Container(
                      height: 30.h,
                      alignment: Alignment.center,
                      child: Icon(Icons.close,color: Colors.white,size: 20.sp,)
                  ),
                )
            ),
            Positioned(
                top: 110.h,
                height: 165.h,
                left: 90.w,
                right: 90.w,
                child: Obx(() => authType.value == '1'?Image.asset("assets/images/reader_big.png")
                    :initialize.value?Align(
                      child:  Transform.scale(
                        scale: 2,
                        child: ClipOval(
                          clipper: ClipperOvalPath(80.w,40.h),
                          child: AspectRatio(
                              aspectRatio: 0.56,
                              child: CameraPreview(controller!)
                          ),
                        ),
                      )
                    )
                    :const SizedBox()
                )
            ),
            Positioned(
                top: 296.h,
                left: 40.w,
                right: 40.w,
                child: InkWell(
                  onTap: (){
                    if(authType.value == '2'){
                      _onTap('1');
                    }

                  },
                  child: Obx(() => Image.asset("assets/images/${authType.value == '1'?'reader_select':'reader_un_select'}.png",width: 60.w,fit: BoxFit.fitWidth,),)
                )
            ),
            Positioned(
                top: 344.h,
                left: 40.w,
                right: 40.w,
                child: InkWell(
                  onTap: (){
                    if(authType.value == '1'){
                      _onTap('2');
                    }
                  },
                  child: Obx(() => Image.asset("assets/images/${authType.value == '2'?'face_select':'face_un_select'}.png",width: 60.w,fit: BoxFit.fitWidth,),)
                )
            ),
          ],
        ),
      ),
    );
  }

  _onTap(tap){
    if(tap == '1'){
      authType.value = '1';
      idSerialPortHelper = SerialPortHelper(settingEntity.idPort??"/dev/ttyS0",115200);
      tts.speak('请刷读者卡');
      _disposeCamera();
    }else{
      authType.value = '2';
      idSerialPortHelper?.close();
      idSerialPortHelper = null;
      tts.speak('请刷人脸');
      _openCamera();
    }

  }



}